﻿#include "salesorder.h"
#include "ui_salesorder.h"

salesorder::salesorder(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::salesorder)
{
    ui->setupUi(this);
    //销售产品明细表

//    ui->tableWidget->horizontalHeader()->ResizeToContents;//试图小界面滚轮大界面自适应宽度但未遂
    ui->tableWidget->setColumnWidth(1, 800);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//适应

//    ui->tableWidget->verticalHeader()->setVisible(false);
    ui->tableWidget->setFocusPolicy(Qt::NoFocus);
    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Fixed);//第一列“产品选择”宽度设置
    ui->tableWidget->setColumnWidth(1,150);
    RightClickMenu=new QMenu(ui->tableWidget);

    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickAddRow(QAction*)));
    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDeleteRow(QAction*)));

    //送货计划表
    ui->tableWidget_3->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//适应
//    ui->tableWidget_3->verticalHeader()->setVisible(false);
    ui->tableWidget_3->setFocusPolicy(Qt::NoFocus);
    ui->tableWidget_3->setContextMenuPolicy(Qt::CustomContextMenu);


    connect(ui->tableWidget_3,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
//    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickAddRow(QAction*)));
//    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDeleteRow(QAction*)));

    //右键插入删除
    m_addAction=new QAction(QString::fromUtf8("插入"),this);
    m_deleteAction=new QAction(QString::fromUtf8("删除"),this);
    RightClickMenu->addAction(m_addAction);
    RightClickMenu->addAction(m_deleteAction);

    //客户信息选择
//    dc2=new clientchoose();
//    connect(dc2,SIGNAL(getStr(QString&)), this, SLOT(setStr(QString&)));
//    ui->storage_combo->addItems(WarehouseList());
//    ui->storage_combo->setCurrentIndex(-1);

}

salesorder::~salesorder()
{
    delete ui;
}

//void salesorder::ClientChoose()
//{
//   //选择客户
//   connect(ui->pushButton_2, &QPushButton::clicked, this, &salesorder::on_pushButton_2_clicked);
//}

//void salesorder::setStr(QString &str)
//{
//    qDebug()<<str;
//    ui->lineEdit->setText(str);
//}
QString salesorder::tableCellText(int row, int column)
{
    switch (column) {
    case 0:
    {
        QComboBox *cbbox = (QComboBox*)( ui->tableWidget_3->cellWidget(row, column));
        return cbbox->currentText();
        break;
    }
    case 1:
    {
        DateEdit *cbbox = (DateEdit*)( ui->tableWidget_3->cellWidget(row, column));
        return cbbox->currentText();
        break;
    }
    default:
        break;
    }
    return nullptr;
}
//初始化商品明细表
void salesorder::RowInit(QTableWidget *T,int index)
{
    T->insertRow(index); //在最后一行的后面插入一行

    //在插入的行中输入产品选择按钮从数据库获得产品数据
    QPushButton *choose_btn = new QPushButton();
    choose_btn->setObjectName("choose_btn" + QString::number(index));
    choose_btn->setProperty("type", "databaseBtn"); //数据库按钮样式

    QWidget *widget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setMargin(0);//一定要有
    layout->addWidget(choose_btn);
    layout->setAlignment(choose_btn, Qt::AlignCenter);//控件在布局中居中显示
    widget->setLayout(layout);

    T->setCellWidget(index, 0, widget);//放在表格第1列
    connect(choose_btn, &QPushButton::clicked, this, &salesorder::choose_btn_clicked);

    for(int i=0;i<T->columnCount();i++)
    {
        if(i==0)    //为按钮列
            continue;
        QTableWidgetItem *item = new QTableWidgetItem();
        T->setItem(index,i,item);
        T->item(index,i)->setTextAlignment(Qt::AlignCenter);
    }
   DetailIDGenerate(index);
}
//初始化配送表
void salesorder::RowInit2(QTableWidget *T,int index)
{
    T->insertRow(index); //在最后一行的后面插入一行
    QComboBox *deliveryLot=new QComboBox();
    deliveryLot->addItems(DeliveryLot());
    deliveryLot->setCurrentIndex(-1);
    deliveryLot->setProperty("type","comboBox");

    DateEdit *scheduledDeliveryDate=new DateEdit();
    scheduledDeliveryDate->setProperty("type","datetime");
//    QWidget *widget = new QWidget();
//    QHBoxLayout *layout = new QHBoxLayout();
//    layout->setMargin(0);//一定要有
//    layout->addWidget(deliveryLot);
//    layout->setAlignment(deliveryLot, Qt::AlignCenter);//控件在布局中居中显示
//    widget->setLayout(layout);

    T->setCellWidget(index, 0, deliveryLot);//放在表格第1列
    T->setCellWidget(index, 1, scheduledDeliveryDate);//放在表格第2列

    for(int i=0;i<T->columnCount();i++)
    {
        if(i==0)    //为按钮列
            continue;
        QTableWidgetItem *item = new QTableWidgetItem();
        T->setItem(index,i,item);
        T->item(index,i)->setTextAlignment(Qt::AlignCenter);
    }
}

void salesorder::RowDelete(QTableWidget *T,int index)
{
    if(index!=-1)
    {
        for(int i=0;i<T->columnCount();i++)
        {
            QWidget *widget=T->cellWidget(index,i);
            //确保不为空
            if(widget)
            {
                T->removeCellWidget(index,i);
                delete widget;  //释放
            }
        }
        T->removeRow(index);
    //    DetailIDGenerate(index);
    }
}


void salesorder::RightClickSlot(QPoint pos)
{
   if(ui->tableWidget->geometry().contains(pos))
   {
       QModelIndex index =ui->tableWidget->indexAt(pos);    //找到tableview当前位置信息
       tbwgt = ui->tableWidget;
       iPosRow = index.row();    //获取到了当前右键所选的行数
       if(index.isValid())        //如果行数有效，则显示菜单
       {
           RightClickMenu->exec(QCursor::pos());
       }
   }
   else
   {
       QModelIndex index =ui->tableWidget_3->indexAt(pos);    //找到tableview当前位置信息
       tbwgt = ui->tableWidget_3;
       iPosRow = index.row();    //获取到了当前右键所选的行数
       if(index.isValid())        //如果行数有效，则显示菜单
       {
           RightClickMenu->exec(QCursor::pos());
       }
   }


}

void salesorder::RightClickAddRow(QAction *act)
{
    if(act->text() == QString::fromUtf8("插入"))   //选中了插入这个菜单
    {
//        RowInit(ui->tableWidget,iPosRow);
//        RowInit2(ui->tableWidget_3,iPosRow);
        if(tbwgt == ui->tableWidget){
            RowInit(tbwgt, iPosRow);
        }else{
            RowInit2(tbwgt,iPosRow);
        }
    }
}

void salesorder::RightClickDeleteRow(QAction *act)
{
    if(act->text() == QString::fromUtf8("删除"))   //选中了删除这个菜单
    {
//        RowDelete(ui->tableWidget,iPosRow);
//        RowDelete(ui->tableWidget_3,iPosRow);
        RowDelete(tbwgt, iPosRow);
    }
}

void salesorder::on_pushButton_2_clicked()
{
    dc=new DataChoose();
    dc->setTitle("选择客户");
    dc->myModel->setQuery(QString("select * from 客户信息表"));
    dc->show();
    connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
            this, [this](const QModelIndexList& list)
    {
                ui->lineEdit->setText(list[0].data().toString());
                ui->lineEdit_2->setText(list[1].data().toString());
                ui->lineEdit_4->setText(list[2].data().toString());
                ui->lineEdit_8->setText(list[3].data().toString());
                ui->lineEdit_7->setText(list[4].data().toString());
//                IDGenerate();       //生成入库编号
//                DetailIDGenerate(0);  //刷新入库详细信息
    });

}

void salesorder::choose_btn_clicked()
{
    QPushButton* btn = qobject_cast<QPushButton*>(this->sender());//判断触发信号的对象
    if (btn == nullptr)
        return;

    // 获取按钮所在的行
    QModelIndex qIndex = ui->tableWidget->indexAt(QPoint(btn->parentWidget()->frameGeometry().x(), btn->parentWidget()->frameGeometry().y()));
    row = qIndex.row();

    //按钮状态选择
    if(btn->property("type")=="check")
    {
        btn->setProperty("type","checked");
        style()->polish(btn);
        vecItemIndex.push_back(row);//存储选中的行号
    }
    else if(btn->property("type")=="checked")
    {
        btn->setProperty("type","check");
        style()->polish(btn);
        vecItemIndex.erase(std::remove(vecItemIndex.begin(), vecItemIndex.end(), row), vecItemIndex.end()); //删除选中的行号
    }
    else if(btn->property("type")=="databaseBtn")
    {
        //创建数据选择子界面
        dc=new DataChoose();
        dc->setTitle("选择产品");
        dc->myModel->setQuery(QString("SELECT  ProductName, ProductType,ProductCode,StockQty FROM product_data_table"));
        dc->myModel->setHeaderData(0,Qt::Horizontal,"产品名称");
        dc->myModel->setHeaderData(1,Qt::Horizontal,"产品属性");
        dc->myModel->setHeaderData(2,Qt::Horizontal,"产品编码");
        dc->myModel->setHeaderData(3,Qt::Horizontal,"产品库存");

        dc->show();
        //子界面向主界面传送选择的数据
        connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
                this, [this](const QModelIndexList& list)
        {
              //  QTableWidgetItem *item = new QTableWidgetItem(list[i].data().toString());
                    ui->tableWidget->item(row,2)->setText(list[0].data().toString());
                    ui->tableWidget->item(row,3)->setText(list[1].data().toString());
                    ui->tableWidget->item(row,4)->setText(list[2].data().toString());
                    ui->tableWidget->item(row,5)->setText(list[3].data().toString());

        });
    }
}


//销售产品明细表格中添加新行
void salesorder::on_add_btn_clicked()
{
    if(ui->add_btn->text()=="添加")
    {
        RowInit(ui->tableWidget,ui->tableWidget->rowCount());
    }
    else if(ui->add_btn->text()=="取消操作")
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,0);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","databaseBtn");
                style()->polish(btn);
            }
        }

        ui->delete_btn->setText(QString::fromUtf8("删除"));
        ui->delete_btn->setProperty("type","deleteData");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("添加"));
        ui->add_btn->setProperty("type","addData");
        style()->polish(ui->add_btn);
    }

}


////表格中删除选中行
void salesorder::on_delete_btn_clicked()
{
    if(ui->delete_btn->text()=="删除")
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,0);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","check");
                style()->polish(btn);
            }
        }
        ui->delete_btn->setText(QString::fromUtf8("删除选中"));
        ui->delete_btn->setProperty("type","deleteConfirm");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("取消操作"));
        ui->add_btn->setProperty("type","deleteCancel");
        style()->polish(ui->add_btn);
    }

    else if(ui->delete_btn->text()=="删除选中")
    {
        sort(vecItemIndex.rbegin(), vecItemIndex.rend());
        for (unsigned int i = 0 ; i < vecItemIndex.size(); i++)
        {
            RowDelete(ui->tableWidget,vecItemIndex[i]);
        }
        vecItemIndex.clear();  //清空容器
        vecItemIndex.shrink_to_fit();   //将容器的容量缩减至和实际存储元素的个数相等，释放内存

        ui->delete_btn->setText(QString::fromUtf8("删除"));
        ui->delete_btn->setProperty("type","deleteData");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("添加"));
        ui->add_btn->setProperty("type","addData");
        style()->polish(ui->add_btn);

        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,0);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","databaseBtn");
                style()->polish(btn);
            }
        }

    }

}

void salesorder::on_add_btn_2_clicked()
{
    //送货计划表
    if(ui->add_btn_2->text()=="添加")
    {
        RowInit2(ui->tableWidget_3,ui->tableWidget_3->rowCount());
    }
    else if(ui->add_btn_2->text()=="取消操作")
    {
//        for(int i=0;i<ui->tableWidget_3->rowCount();i++)
//        {
//            QWidget *widget=ui->tableWidget_3->cellWidget(i,1);
//            if(widget)
//            {
//                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
//                btn->setProperty("type","databaseBtn");
//                style()->polish(btn);
//            }
//        }
        ui->delete_btn_2->setText(QString::fromUtf8("删除"));
        ui->delete_btn_2->setProperty("type","deleteData");
        style()->polish(ui->delete_btn_2);

        ui->add_btn_2->setText(QString::fromUtf8("添加"));
        ui->add_btn_2->setProperty("type","addData");
        style()->polish(ui->add_btn_2);
    }
}

void salesorder::on_delete_btn_2_clicked()
{
    if(ui->delete_btn_2->text()=="删除")
    {
//        for(int i=0;i<ui->tableWidget_3->rowCount();i++)
//        {
//            QWidget *widget=ui->tableWidget_3->cellWidget(i,1);
//            if(widget)
//            {
//                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
//                btn->setProperty("type","check");
//                style()->polish(btn);
//            }
//        }
        ui->delete_btn_2->setText(QString::fromUtf8("删除首行"));
        ui->delete_btn_2->setProperty("type","deleteConfirm");
        style()->polish(ui->delete_btn_2);

        ui->add_btn_2->setText(QString::fromUtf8("取消操作"));
        ui->add_btn_2->setProperty("type","deleteCancel");
        style()->polish(ui->add_btn_2);
    }
     else if(ui->delete_btn_2->text()=="删除首行")
     {
        RowDelete(ui->tableWidget_3,iPosRow);
     }
}

//销售单号生成
void salesorder::IDGenerate()
{

    QString time=ui->comboBox_2->dateToStr().remove(QChar('-'), Qt::CaseInsensitive),   //去除字符‘-’
            limit = "XSDD";

    limit += time;
    QSqlQuery query= mydb->SortData("订单统计表","销售订单编号",false,"销售订单编号",limit); //降序排列

    if(query.next())
    {
            qDebug()<<query.lastError()<<query.value(0).toString();
        QString str=query.value(7).toString();
        QString num=NumberIncrease(str.right(3)); //截取后3位,自增
        ui->lineEdit_9->setText(limit+"-"+num);
    }
    else
        ui->lineEdit_9->setText(limit+"-"+"001");
}

// 销售详细单号生成
//eg: XSDD 20231023 001 01 , 17位
void salesorder::DetailIDGenerate(int index)
{
    if(ui->tableWidget->rowCount()==0 || ui->lineEdit_9->text()==nullptr)
        return;

    QString limit=ui->lineEdit_9->text();
    for(int i=index; i<ui->tableWidget->rowCount(); i++)
    {
        if(i==0)
            ui->tableWidget->item(i,1)->setText(limit+"-01");
        else
        {
            QString num=NumberIncrease(ui->tableWidget->item(i-1,1)->text().right(2)); //截取上一单元格后两位,自增
            ui->tableWidget->item(i,1)->setText(limit+"-"+num);
        }
    }
}


void salesorder::on_comboBox_2_editTextChanged(const QString &arg1)
{
    IDGenerate();
    DetailIDGenerate(0);
}

//销售员选择
void salesorder::on_pushButton_3_clicked()
{
    //创建数据选择子界面
    dc=new DataChoose();
    dc->setTitle("选择销售员");
    dc->myModel->setQuery("SELECT id, username, position FROM dm_user WHERE position = '销售员' " );
    dc->myModel->setHeaderData(0,Qt::Horizontal,"编号");
    dc->myModel->setHeaderData(1,Qt::Horizontal,"姓名");
    dc->myModel->setHeaderData(2,Qt::Horizontal,"职位");
    dc->show();
    //子界面向主界面传送选择的数据
    connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
            this, [this](const QModelIndexList& list)
    {
        //ui->pushButton_3->setText(list[0].data().toString() + "(" + list[1].data().toString() + ")");
        ui->pushButton_3->setText(list[1].data().toString());
        ui->pushButton_3->setProperty("type","ID");
        style()->polish(ui->pushButton_3);

    });
}

QStringList  salesorder::DeliveryLot()
{
    QStringList list;
    list <<"整批" <<"第一批" <<"第二批"<<"第三批";
    return list;
}

//提交
void salesorder::on_pushButton_clicked()
{
        if(ui->lineEdit->text()==nullptr)
        {
            warning(this,"未选择客户");
            return;
        }
        if(ui->comboBox_2->currentText()==nullptr)
        {
            warning(this,"未选择订单日期");
            return;
        }

        if(ui->pushButton_3->text()==nullptr)
        {
            warning(this,"未选择销售员");
            return;
        }
//        if(ui->storage_combo->currentIndex()==-1)
//        {
//            warning(this,"未选择入库仓库");
//            return;
//        }
        if(ui->tableWidget->rowCount()==0)
        {
            warning(this,"未录入产品信息");
            return;
        }
        for(int j=0;j<ui->tableWidget->rowCount();j++)
        {
            if(ui->tableWidget->item(j,3)->text()==nullptr)
            {
                warning(this,"未选择产品");
                return;
            }
            if(ui->tableWidget->item(j,6)->text()==nullptr)
            {
                warning(this,"未填写销售数量");
                return;
            }
            if(ui->tableWidget->item(j,7)->text()==nullptr)
            {
                warning(this,"未填写销售单价");
                return;
            }
            if(ui->tableWidget->item(j,8)->text()==nullptr)
            {
                warning(this,"未选择售价合计");
                return;
            }
        }
        if(ui->tableWidget_3->rowCount()==0)
        {
            warning(this,"未填写送货计划信息");
            return;
        }
        for(int j=0;j<ui->tableWidget_3->rowCount();j++)
        {
            //ui->tableWidget->cellWidget(row, column)
            if(tableCellText(j, 0)==nullptr)
            {
                warning(this,"未选择送货批次");
                return;
            }
            if(tableCellText(j, 1)==nullptr)
            {
                warning(this,"未填写计划送货日期");
                return;
            }
            if(ui->tableWidget_3->item(j,2)->text()==nullptr)
            {
                warning(this,"未填写计划送货内容备注");
                return;
            }
        }

    int ret = QMessageBox::question(this, "上传销售订单","确认上传？", QMessageBox::Yes, QMessageBox::No);
    if(ret == QMessageBox::Yes)
    {

        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QSqlQuery query;
            //插入 入库详细信息表

            query.prepare(QString("INSERT INTO 订单统计表(客户名称,客户类别,客户编码,客户联系人姓名,客户联系人手机,销售员,订单签订日期,销售订单编号,"
                                  "销售订单详细编号,产品名称,产品属性,产品编码,当前可用库存数量,销售数量,销售单价,售价合计,"
                                  "客户详细地址,送货批次,计划送货日期,计划送货内容备注)"
                                " VALUES ('%1','%2','%3','%4','%5','%6','%7','%8',"
                                  "'%9','%10','%11','%12','%13','%14','%15','%16','%17',"
                                  "'%18','%19','%20');")
                          .arg(ui->lineEdit->text()).arg(ui->lineEdit_2->text()).arg(ui->lineEdit_4->text()).arg(ui->lineEdit_8->text()).arg(ui->lineEdit_7->text())
                          .arg(ui->pushButton_3->text()).arg(ui->comboBox_2->currentText()).arg(ui->lineEdit_9->text()).arg(ui->tableWidget->item(i,1)->text())
                          .arg(ui->tableWidget->item(i,2)->text()).arg(ui->tableWidget->item(i,3)->text()).arg(ui->tableWidget->item(i,4)->text()).arg(ui->tableWidget->item(i,5)->text())
                          .arg(ui->tableWidget->item(i,6)->text()).arg(ui->tableWidget->item(i,7)->text()).arg(ui->tableWidget->item(i,8)->text())
                          .arg(ui->lineEdit_3->text()).arg(tableCellText(i, 0)).arg(tableCellText(i, 1)).arg(tableCellText(i, 2)));
            if(!query.exec())
            {
                qDebug()<<query.lastError();
                warning(this,"上传失败");
                return;
            }
            query.clear();  //清空sql语句
         }
        QMessageBox::information(this, "上传销售订单","上传成功");
        this->clear();
    }
}


void salesorder::clear()
{
    ui->lineEdit->setText("");
    ui->lineEdit_2->setText("");
    ui->lineEdit_3->setText("");
    ui->lineEdit_4->setText("");
    ui->lineEdit_8->setText("");
    ui->lineEdit_7->setText("");
    ui->lineEdit_9->setText("");
    ui->comboBox_2->setEditText("");
//    ui->storage_combo->setCurrentIndex(-1);
    ui->pushButton_3->setText("");

    for(int i = ui->tableWidget->rowCount()-1; i>=0 ; i--)
    {
        RowDelete(ui->tableWidget,i);
    }
    for(int i = ui->tableWidget_3->rowCount()-1; i>=0 ; i--)
    {
        RowDelete(ui->tableWidget_3,i);
    }
}
